package generateparentheses;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hht
 * @ClassName Solution
 * @Description TODO
 * @Date 2019/6/20 20:37
 * @VERSION 1.0
 */
public class Solution {
    public static void main(String[] args) {
        List list = new Solution().generateParenthesis(3);
        System.out.println(list);
    }

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        generate(result, new StringBuilder(), n, n);

        return result;
    }


    public void generate(List<String> result, StringBuilder sb, int open, int close) {

        if (close < open) return; // Cannot form valid string from this branching, return early

        if (close == 0 && open == 0) { // Completed a valid result! Store it
            result.add(sb.toString());
            return;
        }

        // At this point, we are able to continue branching. Conditions are still valid.

        if (open > 0) { // Branch on available open parens
            sb.append("(");
            generate(result, sb, open - 1, close);
            sb.deleteCharAt(sb.length() - 1);
        }

        if (close > 0) { // Branch on available closing parens
            sb.append(")");
            generate(result, sb, open, close - 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
